package com.clothing.controller;

import com.clothing.CommonAttributes;
import com.clothing.service.FileService;
import com.clothing.utils.AjaxMsg;
import com.clothing.utils.Utils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName: CommonController
 * @Description: TODO(公共)
 * @author Charles.Tao
 * @date 2017年9月5日 下午4:57:05
 * @version 1.0
 */
@Controller
@RequestMapping("/common")
public class CommonController extends BaseController
{
    @Autowired
    private FileService fileService;

    /**
     * @Title: upload
     * @Description: TODO(上传)
     * @param @param file
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
     */
    @RequestMapping(value = "/file/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file)
    {
        if (null == file || file.isEmpty())
        {
            return getParameterErrorMsg();
        }

        String ext = file.getOriginalFilename().toLowerCase();

        if (!FilenameUtils.isExtension(ext, CommonAttributes.IMAGE_UPLOAD_EXTENSIONS))
        {
            return getParameterErrorMsg();
        }

        String url = fileService.upload(file);

        if (null == url)
        {
            return AjaxMsg.failed("上传失败");
        }

        return AjaxMsg.success(url);
    }

    /**
     * @Title: delete
     * @Description: TODO(删除图片)
     * @param @param fileUrl
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(String[] fileUrls)
    {
        if (!Utils.isEmpty(fileUrls))
        {
            for (String fileUrl : fileUrls)
            {
                if (Utils.isEmpty(fileUrl))
                {
                    continue;
                }

                fileService.deleteFile(fileUrl);
            }
        }

        return AjaxMsg.success();
    }
}
